package git.soulbgm.handle;

import git.soulbgm.service.TcpClient;
import git.soulbgm.utils.ByteUtil;
import git.soulbgm.utils.IpUtil;
import git.soulbgm.utils.Sequence;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author 贺瑞杰
 * @version V1.0
 * @date 2018-10-17 13:39
 * @description
 */
@ChannelHandler.Sharable
@Component
@Slf4j
public class TcpSimpleHandle extends SimpleChannelInboundHandler<ByteBuf> {

    @Autowired
    private TcpClient tcpClient;

    private Sequence sequence = new Sequence(1, 1);

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (IdleState.READER_IDLE.equals(event.state())) {
                // 长期未收到服务端推送的消息
                // 可以选择重新连接
//                tcpClient.doConnect();
            } else if (IdleState.WRITER_IDLE.equals(event.state())) {
                // 长期未向服务端推送消息
                // 发送心跳包
//                ctx.channel().writeAndFlush(ByteUtil.stringToByteBuf("111222333$_$"));
            } else if (IdleState.ALL_IDLE.equals(event.state())) {
                // 长期未收到服务端推送的消息并且也长期未向服务端推送消息
            }
        }
    }

    /**
     * 当客户端连接断开时调用
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        connectionRetry(ctx);
    }

    /**
     * 连接重试
     *
     * @param ctx
     */
    private void connectionRetry(ChannelHandlerContext ctx) {
        ctx.channel().eventLoop().schedule(new Runnable() {
            @Override
            public void run() {
                log.warn("连接中断，3秒后重试~~");
                tcpClient.doConnect();
            }
        }, 3L, TimeUnit.SECONDS);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        byte[] bytes = ByteUtil.byteBufToByteArray(msg);
        String str = new String(bytes);
        log.info("消息:{}", str);
        ctx.channel().writeAndFlush(ByteUtil.stringToByteBuf(sequence.nextId() + "$_$"));
    }
}
